<?php

namespace app\admin\middleware;

use think\Request;
use think\Response;
use app\admin\service\AuthService;

use Closure;
use ReflectionClass;

class CheckAuth
{
    public function handle(Request $request, Closure $next): Response
    {

        
        $adminInfo = $request->adminInfo;
        if (empty($adminInfo)) return $next($request);

        $controller = $request->controller();
        if (empty($controller)) return $next($request);
        if (str_contains($controller, '.')) $controller = str_replace('.', '\\', $controller);
        $action          = $request->action();
        $controllerClass = 'app\\admin\\controller\\' . $controller;
        $classObj        = new ReflectionClass($controllerClass);
        $properties      = $classObj->getDefaultProperties();

        // 不需要验证登录的方法
        $noNeedRight = $properties['noNeedRight'] ?? ['*'];
        if (in_array('*', $noNeedRight) || in_array($action, $noNeedRight)) {
            return $next($request);
        }


        
        $authService = app(AuthService::class, ['admin_id' => $request->adminInfo->id]);
        $node = $authService->getCurrentNode();
        $authService->check($node);


        return $next($request);
    }
}